package com.sinder.campus_prophet.web.jwgl;

import cc.lyceum.api.thxy.jwgl.ThxyJwgl;
import com.sinder.campus_prophet.core.annotation.RequestLimit;
import com.sinder.campus_prophet.core.global.ResponseMessage;
import com.sinder.campus_prophet.service.jwgl.TbJwglInfoService;
import com.sinder.campus_prophet.service.jwgl.bean.dto.BindJwglDto;
import com.sinder.campus_prophet.service.jwgl.bean.dto.SynJwglDto;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.sql.SQLException;

/**
 * 教务管理Api
 *
 * @author sinder
 * Date 2023/3/19/18:34
 **/
@RestController
@RequestMapping("jwgl")
@Slf4j
public class JwglApiController {
    private final TbJwglInfoService jwglInfoService;

    public JwglApiController(TbJwglInfoService jwglInfoService) {
        this.jwglInfoService = jwglInfoService;
    }

    /**
     * 教务系统数据同步
     * RequestLimit(count=1, time=1800000)：半小时内不能超过1次同步操作，避免重复点击，恶意请求
     *
     * @param synJwglDto 用户参数
     * @return
     */
    @RequestLimit(count = 3, time = 600000)
    @PostMapping("synJwglData")
    public ResponseMessage synJwglData(@Validated @RequestBody SynJwglDto synJwglDto, HttpServletRequest request) {
        // 先校验账号密码是否正确
        ThxyJwgl jwgl = jwglInfoService.checkJwglLogin(synJwglDto.getOpenId(), request);
        try {
            return jwglInfoService.synJwglData(synJwglDto, jwgl);
        } catch (SQLException e) {
            throw new RuntimeException("数据异常：" + e.getMessage());
        }
    }

    /**
     * 绑定教务系统
     * 半小时内不能超过5次绑定
     * @param bindJwgl
     * @return
     */
    @RequestLimit(count = 5, time = 600000)
    @PostMapping("bindJwgl")
    public ResponseMessage bindJwgl(@RequestBody @Validated BindJwglDto bindJwgl) {
        return jwglInfoService.bindJwgl(bindJwgl)
                ? ResponseMessage.createBySuccessMessage("绑定教务系统成功")
                : ResponseMessage.createByErrorMessage("该账号已绑定，请检查数据");
    }

    /**
     * 查询教务系统信息
     * @param openId
     * @return
     */
    @GetMapping("getJwglInfo")
    public ResponseMessage getJwglInfo(@NotBlank(message = "用户标识不能为空") String openId) {
        return jwglInfoService.getJwglInfo(openId);
    }

    /**
     * 修改绑定，重新绑定
     * 半小时内不能超过5次绑定
     * @param bindJwgl
     * @return
     */
    @RequestLimit(count = 5, time = 600000)
    @PostMapping("bindUpJwgl")
    public ResponseMessage bindUpJwgl(@RequestBody @Validated BindJwglDto bindJwgl) {
        return jwglInfoService.bindUpJwgl(bindJwgl)
                ? ResponseMessage.createBySuccessMessage("更新教务信息成功")
                : ResponseMessage.createByErrorMessage("更新异常，请稍后重试");
    }
}
